import 'package:pixelyear/bean/StringBean.dart';
import 'package:pixelyear/sql/Sql.dart';
import 'package:sqflite/sqflite.dart';

class NoteSqlUtils extends Sql {
  NoteSqlUtils._privateConstructor();

  static final NoteSqlUtils _instance = NoteSqlUtils._privateConstructor();

  static NoteSqlUtils get instance => _instance;

  void addNote(StringBean data) async {
    bool exists = await isExists(data.time);
    Database db = await getDb();
    if (!exists) {
      await db.rawInsert(
          "insert into " + Sql.noteName + " (date,note) values(?,?)",
          [data.time, data.data]);
      await db.close();
    } else {
      await db.rawUpdate("update " + Sql.noteName + " set note=? where date=?",
          [data.data, data.time]);
      await db.close();
    }
  }

  void deleteNote(String date) async {
    Database db = await getDb();
    db.rawDelete("delete from " + Sql.noteName + " where date=?", [date]);
    await db.close();
  }

  Future<StringBean> getData(String time) async {
    Database db = await getDb();
    List<Map<String, dynamic>> cursor = await db
        .rawQuery("select * from " + Sql.noteName + " where date = ?", [time]);
    if (cursor.isNotEmpty) {
      StringBean stringBean = StringBean(
        cursor[0]["date"],
        cursor[0]["note"],
      );
      await db.close();
      return stringBean;
    }
    await db.close();
    return null;
  }

  Future<bool> isExists(String time) async {
    Database db = await getDb();
    List<Map<String, dynamic>> cursor = await db
        .rawQuery("select * from " + Sql.noteName + " where date = ?", [time]);
    await db.close();
    return cursor.isNotEmpty;
  }
}
